package com.example.demo.config;




import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.example.demo.entity.Buy;
import com.example.demo.entity.PayVo;
import com.example.demo.services.test;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Component
@Data
public class AlipayTemplate {

    @Value("${pay.alibaba.appid}")
    private String appId;

    @Value("${pay.alibaba.merchantPrivateKey}")
    private String merchantPrivateKey;

    @Value("${pay.alibaba.alipayPublicKey}")
    private String alipayPublicKey;

    @Value("${pay.alibaba.notifyUrl}")
    private String notifyUrl;

    @Value("${pay.alibaba.returnUrl}")
    private String returnUrl;

    @Value("${pay.alibaba.signType}")
    private String signType;

    @Value("${pay.alibaba.charset}")
    private String charset;

    @Value("${pay.alibaba.timeout}")
    private String timeout;

    @Value("${pay.alibaba.gatewayUrl}")
    private String gatewayUrl;

    public String pay(PayVo vo, HttpSession session) throws AlipayApiException, UnsupportedEncodingException {
        AlipayClient alipayClient=new DefaultAlipayClient(gatewayUrl,
                appId,merchantPrivateKey,"json",
                charset,alipayPublicKey,signType);
        //创建一个支付宝页面付款请求类 实例化
        AlipayTradePagePayRequest aliPayRequest=new AlipayTradePagePayRequest();
        //设置返回网址就是支付成功后要跳转的网址
        aliPayRequest.setReturnUrl(returnUrl);
        //设置返回通知网址 要用外网能访问到的 我这里用的是花生米穿透内网
        aliPayRequest.setNotifyUrl(notifyUrl);
        //商品订单号，商户网站订单系统中的唯一订单号，必填 用雪花算法生成
        String out_trade_no=vo.getOutTradeNo();
        //付款金额，必填
        String total_amount=vo.getTotalAmount();
        //订单名称必填
        String subject=vo.getSubject();
        //商品描述，可空
        String body=vo.getBody();
        //买家信息
        String buyer_id=vo.getBuyerId();
        Object userId=session.getAttribute("userId");
        //传入session
//        Buy userId=(Buy) session.getAttribute("userId");
//        Buy test=new Buy();
//        test.setUserId(vo.getUserId());
//        test.setUserName(vo.getUserName());
//        test.setArticleId(vo.getArticleId());
//        test.setArticleTitle(vo.getBody());
//        Integer price=Integer.valueOf(vo.getTotalAmount());
//        test.setPrice(price);
        String test=String.valueOf(userId);
//        String passback=new String(test);
        String str= URLEncoder.encode(test,"UTF-8");

        aliPayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\""+timeout+"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\","+"\"buyer_id\":\""+buyer_id+"\","+"\"passback_params\":\""+str+"\"}");

        //会收到支付宝的响应，响应的是一个页面，只要浏览器显示这个页面,就会自动来到支付宝的收银页面

        return alipayClient.pageExecute(aliPayRequest).getBody();
    }

    public void test() throws AlipayApiException {
        AlipayClient alipayClient=new DefaultAlipayClient(gatewayUrl,
                appId,merchantPrivateKey,"json",
                charset,alipayPublicKey,signType);
        AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
        request.setNotifyUrl(notifyUrl);
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", "20210817010101003");
        bizContent.put("total_amount", 0.01);
        bizContent.put("subject", "测试商品");
        bizContent.put("buyer_id", "2088102146225135");
        bizContent.put("timeout_express", "10m");
        bizContent.put("trade_no",null);
        bizContent.put("sub_msg","2088102146225135");
        bizContent.put("sub_code","20210817010101003");

//// 商品明细信息，按需传入
//JSONArray goodsDetail = new JSONArray();
//JSONObject goods1 = new JSONObject();
//goods1.put("goods_id", "goodsNo1");
//goods1.put("goods_name", "子商品1");
//goods1.put("quantity", 1);
//goods1.put("price", 0.01);
//goodsDetail.add(goods1);
//bizContent.put("goods_detail", goodsDetail);

//// 扩展信息，按需传入
//JSONObject extendParams = new JSONObject();
//extendParams.put("sys_service_provider_id", "2088511833207846");
//bizContent.put("extend_params", extendParams);

//// 结算信息，按需传入
//JSONObject settleInfo = new JSONObject();
//JSONArray settleDetailInfos = new JSONArray();
//JSONObject settleDetail = new JSONObject();
//settleDetail.put("trans_in_type", "defaultSettle");
//settleDetail.put("amount", 0.01);
//settleDetailInfos.add(settleDetail);
//settleInfo.put("settle_detail_infos", settleDetailInfos);
//bizContent.put("settle_info", settleInfo);

//// 二级商户信息，按需传入
//JSONObject subMerchant = new JSONObject();
//subMerchant.put("merchant_id", "2088000603999128");
//bizContent.put("sub_merchant", subMerchant);

//// 业务参数信息，按需传入
//JSONObject businessParams = new JSONObject();
//businessParams.put("busi_params_key", "busiParamsValue");
//bizContent.put("business_params", businessParams);

//// 营销信息，按需传入
//JSONObject promoParams = new JSONObject();
//promoParams.put("promo_params_key", "promoParamsValue");
//bizContent.put("promo_params", promoParams);

        request.setBizContent(bizContent.toString());
        AlipayTradeCreateResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }

}
